package com.tjec.common.utils.ftp;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.tjec.common.utils.StringUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.tjec.project.system.domain.BmsAttachmentChunk;
import org.springframework.beans.factory.annotation.Value;

public class FavFTPUtil {

	/**
	 * 上传文件（可供Action/Controller层使用）
	 * 
	 * @param hostname    FTP服务器地址
	 * @param port        FTP服务器端口号
	 * @param username    FTP登录帐号
	 * @param password    FTP登录密码
	 * @param pathname    FTP服务器保存目录
	 * @param fileName    上传到FTP服务器后的文件名称
	 * @param inputStream 输入文件流
	 * @return
	 */
	public static boolean uploadFile(String hostname, int port, String username, String password, String pathname,
			String fileName, InputStream inputStream) {
		boolean flag = false;
		FTPClient ftpClient = new FTPClient();
		ftpClient.setControlEncoding("UTF-8");
		try {
			// 连接FTP服务器
			ftpClient.connect(hostname, port);
			// 登录FTP服务器
			ftpClient.login(username, password);
			// 是否成功登录FTP服务器
			int replyCode = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				return flag;
			}

			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.makeDirectory(pathname);
			ftpClient.changeWorkingDirectory(pathname);
			ftpClient.storeFile(fileName, inputStream);
			inputStream.close();
			ftpClient.logout();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

	/**
	 * 上传文件（可供Action/Controller层使用）
	 *
	 * @param hostname    FTP服务器地址
	 * @param port        FTP服务器端口号
	 * @param username    FTP登录帐号
	 * @param password    FTP登录密码
	 * @param pathname    FTP服务器保存目录
	 * @param fileName    上传到FTP服务器后的文件名称
	 * @param inputStream 输入文件流
	 * @returns
	 */
	public static boolean uploadFiles(String hostname, int port, String username, String password,String pathroot, String pathname,
									 String fileName, InputStream inputStream) {
		boolean flag = false;
		FTPClient ftpClient = new FTPClient();
		ftpClient.setControlEncoding("UTF-8");
		try {
			// 连接FTP服务器
			ftpClient.connect(hostname, port);
			// 登录FTP服务器
			ftpClient.login(username, password);
			// 是否成功登录FTP服务器
			int replyCode = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				return flag;
			}
			String[] split = pathname.split("/");
			for (String str : split) {
				if (StringUtils.isBlank(str)) {
					continue;
				}
				if (!ftpClient.changeWorkingDirectory(str)) {
					System.err.println("不存在");
					boolean makeDirectory = ftpClient.makeDirectory(str);
					boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(str);
					System.err.println(str + "创建：" + makeDirectory + ";切换：" + changeWorkingDirectory);
				} else {
					System.err.println("存在");
				}
			}
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.makeDirectory(pathroot + pathname);
			ftpClient.changeWorkingDirectory(pathroot + pathname);
			ftpClient.storeFile(fileName, inputStream);
			inputStream.close();
			ftpClient.logout();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}


	/**
	 * 文件合并
	 *
	 * @param targetFile
	 * @param folder
	 */
	public static void merge(String hostname, int port, String username, String password, String targetFile, String folder,
			String filename) throws Exception {

		// ChannelSftp chsftp = (ChannelSftp)channel;
		FTPClient ftpClient = new FTPClient();
		ftpClient.setControlEncoding("UTF-8");
		try {
			// 连接FTP服务器
			ftpClient.connect(hostname, port);
			// 登录FTP服务器
			ftpClient.login(username, password);
			int replyCode = ftpClient.getReplyCode();
			System.out.println("登陆结果==》" + replyCode);
			// log.debug("folder:{}",folder);
			ftpClient.cwd(folder);
			ftpClient.enterLocalPassiveMode();
			// 去除所有文件名
			List<BmsAttachmentChunk> list = new ArrayList<>();
			BmsAttachmentChunk bmsAttachmentChunk;
			// FTPFile[] vector = ftpClient.listFiles(folder);
			// for (Object item : vector) {
			FTPFile[] ftpFiles = ftpClient.listFiles(folder);
			for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
				FTPFile file = ftpFiles[i];
				String name = file.getName();
				System.out.println("文件名>>>>>>>>>>>>>>>>" + name);
				if (name.indexOf("-") > 0) {
					bmsAttachmentChunk = new BmsAttachmentChunk();
					bmsAttachmentChunk.setFilename(name);
					list.add(bmsAttachmentChunk);
				}

			}
			
			// 合并文件
			list.stream().filter(a -> !a.getFilename().equals(filename)).sorted((o1, o2) -> {
				String p1 = o1.getFilename();
				String p2 = o2.getFilename();
				int i1 = p1.lastIndexOf("-");
				int i2 = p2.lastIndexOf("-");
				return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1)));
			}).forEach(b -> {
				InputStream in = null;
				try {
					in = ftpClient.retrieveFileStream(b.getFilename());
					byte[] fileData = IOUtils.toByteArray(in);
					System.out.println("数据长度：" + fileData.length);
					InputStream sbs = new ByteArrayInputStream(fileData);
					
					String oldFileName = b.getFilename();
					System.out.println(oldFileName.substring(oldFileName.lastIndexOf("-") + 1));
					if ("1".equals(oldFileName.substring(oldFileName.lastIndexOf("-") + 1))) {
						ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
						ftpClient.makeDirectory(targetFile);
						ftpClient.changeWorkingDirectory(targetFile);
						ftpClient.storeFile(filename, sbs);
						//ftpClient.appendFile(filename, sbs);
						/*OutputStream os = ftpClient.appendFileStream(filename);
						os.write(fileData);
						os.flush();
						os.close();*/
					}
					
					ftpClient.deleteFile(b.getFilename());
					in.close();
					ftpClient.logout();
				} catch (IOException e) {
					e.printStackTrace();
				}

			});
			// chsftp.quit();
			// this.closeServer();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
